<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>logo32x32.png">
    <link rel="stylesheet" type="text/css" href="./index.css" />
    <title>MyApps</title>
  </head>
  <body>
    <script>
      var obpmFilePath = '/obpm'
      var appName = 'points'
      var page_lines = 10 //每页条数
      var page = 1 //页码
      var rowCount = 0 //总数
      var pageCenter = 0
     	var ajax = function (data) {
        return new Promise((resolve, reject) => {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
              if (
                (xhr.status >= 200 && xhr.status < 300) ||
                xhr.status === 304
              ) {
                // resolve(xhr.responseText);
                data.success(xhr.responseText);
              } else {
                reject(xhr.status);
              }
            } else {
              // HTTP请求还在继续...
            }
          };
          xhr.open(data.methods, data.url, data.async);
          xhr.setRequestHeader("content-type", "application/json");

          delete data.methods;
          delete data.url;
          xhr.send(JSON.stringify(data.data));
        });
      };
      function changeInput(input) {
        debugger
        console.log(input,'input')
        if(!input.value) {
          input.value = 1
        }
      }
      //减
      function decrement(btn) {
        debugger
        //获取数量
        let num=btn.nextElementSibling.value
        if(num == 1) {
          btn.classList.add('stopOper')
          return
        }
        if(num<=1){
          num=1
          btn.classList.add('stopOper')
        }else{
          num--
        }
        //重新给数量赋值
        btn.nextElementSibling.value=num
      }
      // 增
      function increment(btn,read_only) {
        if(read_only == 'true') return
        btn.previousElementSibling.previousElementSibling.classList.remove('stopOper')
        let num=btn.previousElementSibling.value
         //修改数量
        if(num == 1000) {
          num = 1000
        }else {
          num++
        }
        //重新把数量赋值给指定位置
        btn.previousElementSibling.value=num
      }
      //兑换
      function exchange(sku) {
        if(confirm('确认是否兑换？')) {
          let quantity = document.getElementById('quantity').value
          let data = {
            sku: sku,
            quantity:quantity,
          }
          let exchangeProduct = {
            methods: "POST",
            url: `${obpmFilePath}/magic-api/${appName}/product_exchange`,
            async: true,
            data:data,
            success: function (result) {
              if (result) {
                if(JSON.parse(result).errcode == 200) {
                  alert('兑换成功！')
                  getProducts()
                }else {
                  let errmsg = JSON.parse(result).errmsg
                  alert(errmsg)
                  getProducts()
                }
              }
            },
          };
          ajax(exchangeProduct); 
        }
      }
      // 中间页码事件
      function centerClick(num) {
        debugger
        page = Number(num)
        for (let i = 0; i < pageCenter; i++) {
          if ((page - 1) === i) {
            document.getElementById("btn_" + (page - 1)).disabled = true
          } else {
            document.getElementById("btn_" + i).disabled = false
          }
        }
        getProducts()
        // pageShow(page, page_lines)
      }
      function getProducts(searchValue) {
        debugger
        let data = {
          sku:'',
          product_name: searchValue ? searchValue :'',
          page_lines:page_lines,
          page:page,
        }
        let product_list = {
          methods: "POST",
          url: `${obpmFilePath}/magic-api/${appName}/product_list`,
          async: true,
          data:data,
          success: function (result) {
            let html = ""
            let productContent = document.getElementById('productContent')
            let noGood = document.getElementById('noGood')
            if (result) {
              if(JSON.parse(result).data) {
                productContent.style.display = ''
                noGood.style.display = ""
                let product_list = JSON.parse(result).data.product_list
                rowCount = JSON.parse(result).data.rowCount
                product_list.forEach((item,index) => {
                  let product_pic = JSON.parse(item.product_pic)[0]
                  let addDom = ''
                  console.log(item.read_only,'item.read_only')
                  if(item.read_only) {
                    addDom = `<button onclick="increment(this,'${item.read_only}')" class="control stopOper">+</button>`
                  }else {
                    addDom = "<button onclick='increment(this)' class='control'>+</button>"
                  }
                  //描述 <div class="sku">商品编号：${item.sku}</div>
                  html += `<div class="product">
                            <img src="${product_pic.url}" alt="">
                            <div class="productName" title="${item.product_name}">${item.product_name}</div>
                            <div class="productdes" title="${item.product_description}">${item.product_description}</div>
                            
                            <div class="counter">
                              <span class="numFont">数&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;量：</span>
                              <span class="num">
                                <button onclick="decrement(this)" class="control stopOper">-</button>
                                <input type="number" class="buyNum" id="quantity" value="1" onchange="changeInput(this)">
                                ${addDom}
                              </span>
                            </div>
                            <div class="exchange">
                            <span class="requiredPoints">${item.required_points}<span class='point'>积分</span></span>
                            `
                  if(item.read_only) {
                    html +=  `<span class="exchangeBtn realonly">立即兑换</span>`
                  }else {
                    // let string = JSON.stringify(item)
                    let sku = item.sku
                    html +=  `<span class="exchangeBtn" onclick="exchange('${sku}')">立即兑换</span>`
                  }
                  html += `</div>
                          </div>`
                })
                let dom = document.getElementById('productList')
                dom.innerHTML = html
              }else {
                noGood.style.display = "block"
                productContent.style.display = 'none'
                pageCenter = 0
                rowCount = 1
                page_lines = 10
              }
              let left = document.getElementById("leftBtn");
              let right = document.getElementById("rightBtn");
              document.getElementById('btn').innerHTML = ''
              pageCenter = Math.ceil(rowCount / page_lines);
              console.log(pageCenter)
              for (let i = 0; i < pageCenter; i++) {
                let para = document.createElement("button");
                para.appendChild(document.createTextNode(i + 1));
                para.id = 'btn_' + i
                para.onclick = function () {
                  centerClick(this.innerHTML)
                };
                document.getElementById('btn').appendChild(para)
              }
              document.getElementById('btn_' + (page - 1)).disabled = true
              if(page == 1 && pageCenter == 1) {
                left.disabled = true;
                right.disabled = true;
              }else if(page == 1) {
                left.disabled = true
                right.disabled = false;
              }else if(page == pageCenter) {
                right.disabled = true;
                left.disabled = false;
              }else {
                left.disabled = false;
                right.disabled = false;
              }
            }
          },
			  };
			  ajax(product_list);
      }      
      function getValue() {
        page = 1
        let searchValue = document.getElementById('search_input').value
        getProducts(searchValue)
      } 
      getProducts()
    </script>
    <div id="main">
      <div id="search">
          <input type="text" id="search_input" placeholder="名称" style="width:220px;">
          <span class="searchBtn" onclick="getValue()">查询</span>
      </div>
      <div id="productContent">
        <div id="productList"></div>
      </div>
      <div id="noGood"><span class="none">暂无商品</span></div>
      <div style="display: flex;justify-content:center;" id="goodPage">
        <button id="leftBtn" onclick="centerClick(page - 1)" disabled><</button>
        <div id="btn"></div>
        <button id="rightBtn" onclick="centerClick(page + 1)">></button>
      <div>
    </div>
  </body>
</html>
